<template>
  <div class="app-container">

    <SearchContent :queryParams="queryParams" @query="handleQuery" @reset="resetQuery">
      <el-col :span="6">
        <el-form-item label="工单状态:" prop="workOrderStatus">
          <el-select v-model="queryParams.workOrderStatus" placeholder="请选择工单状态">
            <el-option v-for="item in dict.type.work_order_status" :label="item.label" :value="item.value"
                       :key="item.value"/>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="合同禀议编号:" prop="contractReportNumber">
          <el-input v-model="queryParams.contractReportNumber" clearable placeholder="请输入合同禀议编号"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="车牌号/车架号:" prop="carNoVinNo">
          <el-input v-model="queryParams.carNoVinNo" clearable placeholder="请输入车牌号/车架号"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="保险工单编号:">
          <el-input v-model="queryParams.workOrderCode" clearable placeholder="请输入保险工单编号"></el-input>
        </el-form-item>
      </el-col>

      <el-col :span="6">
        <el-form-item label="批次号:" prop="flowBusinessId">
          <el-input v-model="queryParams.flowBusinessId" clearable placeholder="请输入批次号"></el-input>
        </el-form-item>
      </el-col>

      <el-col :span="6">
        <el-form-item label="车辆产权:">
          <el-select filterable v-model="queryParams.propertyRightId" clearable placeholder="请选择车辆产权"
                     style="width: 100%">

            <el-option v-for="item in companyOriginList" :label="item.deptName" :value="item.deptId"
                       :key="item.deptId"/>

          </el-select>
        </el-form-item>
      </el-col>

      <el-col :span="6">
        <el-form-item label="车辆归属:">
          <el-select filterable v-model="queryParams.ascriptionId" clearable placeholder="请选择车辆归属"
                     style="width: 100%">

            <el-option v-for="item in companyOriginList" :label="item.deptName" :value="item.deptId"
                       :key="item.deptId"/>

          </el-select>
        </el-form-item>
      </el-col>

      <el-col :span="6">
        <el-form-item label="品牌/车系/车型:">
          <linkage-select @changeNode="linkageChange" v-model="linkageList" placeholder="请选择品牌/车系/车型"/>
        </el-form-item>
      </el-col>

      <el-col :span="6">
        <el-form-item label="采购禀议编号:" prop="procurementReportNumber">
          <el-input v-model="queryParams.procurementReportNumber" clearable placeholder="请输入采购禀议编号"></el-input>
        </el-form-item>
      </el-col>

      <el-col :span="6">
        <el-form-item label="客户名称:" prop="customerName">
          <el-input v-model="queryParams.customerName" clearable placeholder="请输入客户名称"></el-input>
        </el-form-item>
      </el-col>
    </SearchContent>
    <div class="card-wrap card-padding">
      <div class="table-title-wrap justify-end">
        <e-button type="primary" size="mini" @click="handleAdd" v-hasPermi="['insure:newCarInsuranceList:add']">新增
        </e-button>
        <e-button v-if="queryParams.workOrderStatus == 1 || queryParams.workOrderStatus == 5" type="primary" size="mini"
                  :disabled="idList.length === 0" @click="handleBatch"
                  v-hasPermi="['insure:newCarInsuranceList:batch']">
          批量处理
        </e-button>

      </div>
      <table-page :loading="loading" :dataList="dataList" :total="total" :page.sync="queryParams.pageNum"
                  :limit.sync="queryParams.pageSize" @setSizeCurrent="getList" :isSelect="true"
                  @selectionChange="handleSelectionChange" border>
        <template slot="tableColAc">
          <el-table-column label="操作" align="center" fixed="left" width="100">
            <template slot-scope="{row}">
              <el-button size="mini" type="text" @click="viewOpen(row, 'view')"
                         v-hasPermi="['insure:newCarInsuranceList:view']" v-if="row.workOrderStatus != 1">查看
              </el-button>

              <el-button size="mini" type="text" v-hasPermi="['insure:newCarInsuranceList:handle']"
                         v-if="row.workOrderStatus == 1 || row.workOrderStatus == 5" @click="handleWork(row)">处理
              </el-button>

            </template>
          </el-table-column>

        </template>

        <template slot="tableCol">
          <el-table-column align="center" label="保险工单编号" prop="workOrderCode" show-overflow-tooltip
                           min-width="180"/>

          <el-table-column align="center" label="批次号" prop="flowBusinessId" show-overflow-tooltip
                           min-width="180"/>
          <el-table-column align="center" label="合同禀议编号" width="220">
            <template slot-scope="{row}">
              <el-button size="mini" class="enable-text-select" @click="handleToContract(row)" type="text">{{
                  row.contractReportNumber
                }}
              </el-button>
            </template>
          </el-table-column>
          <el-table-column align="center" label="车辆产权" show-overflow-tooltip min-width="160"
                           prop="propertyRightName"/>
          <el-table-column align="center" label="车架号" prop="vinNo" show-overflow-tooltip min-width="180"/>
          <el-table-column align="center" label="车牌号" min-width="100" prop="carNo"/>

          <el-table-column align="center" label="品牌/车型" show-overflow-tooltip min-width="280">
            <template slot-scope="{row}">
              {{ row.brandName }}{{ row.modelName ? '/' + row.modelName : '' }}
            </template>
          </el-table-column>


          <el-table-column align="center" label="车辆归属" show-overflow-tooltip min-width="160" prop="ascription"/>
          <el-table-column align="center" label="车辆运营" show-overflow-tooltip min-width="120"
                           prop="operationsName"/>
          <el-table-column align="center" label="车辆大区" show-overflow-tooltip min-width="160">
            <template #default="{row}">
              <span v-if="row.region">{{ row.region }} </span>

            </template>
          </el-table-column>

          <el-table-column align="center" label="保险类型" width="130">
            <template slot-scope="{row}">
              <span v-show="row.insuranceChannels == 1">我司购买</span>
              <span v-show="row.insuranceChannels == 2">店端投保</span>
              <span v-show="row.insuranceChannels == 3">客户自购</span>
            </template>
          </el-table-column>

          <el-table-column align="center" label="审批状态" show-overflow-tooltip min-width="140" prop="expenseStatus"/>

          <el-table-column align="center" label="工单类型" width="96">
            <template slot-scope="{row}">
              {{ selectDictLabel(dict.type.work_order_type, row.workOrderType) }}工单
            </template>

          </el-table-column>
          <el-table-column align="center" label="客户名称" width="160" show-overflow-tooltip prop="customerName"/>
          <el-table-column align="center" label="工单状态" width="140">
            <template slot-scope="{row}">
              {{ dictsName(dict.type.work_order_status, row.workOrderStatus) }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="车辆状态" width="160" prop="carType">
            <template slot-scope="{row}">
              {{ dictsName(dict.type.car_business_type, row.businessType) }}
            </template>
          </el-table-column>


          <el-table-column align="center" label="采购禀议编号" width="220">
            <template slot-scope="{row}">
              <el-button size="mini" class="enable-text-select" @click="handleToProcurement(row)" type="text">{{
                  row.procurementReportNumber
                }}
              </el-button>
            </template>
          </el-table-column>
          <el-table-column align="center" label="处理人" prop="processedByName" width="120"/>

          <el-table-column align="center" label="处理时间" width="140">
            <template slot-scope="{row}">
              {{ row.processedByTime ? $dayjs(row.processedByTime).format('YYYY-MM-DD') : '' }}

            </template>

          </el-table-column>
          <el-table-column align="center" label="工单创建时间" width="140">
            <template slot-scope="{row}">
              {{ row.createTime }}
            </template>

          </el-table-column>
        </template>
      </table-page>
    </div>

    <!-- 添加或修改测试单表对话框 -->
    <workOrderDialog ref="refAddDialog" @change="handleDialog"/>
  </div>
</template>

<script>
import {getInsuranceWorkList, unifyCheck} from "@/api/cwgd/cwgdApi.js";

import {getToken} from "@/utils/auth";
import {addInsuranceWork} from "@/api/cwgd/inspectApi.js";
import LinkageSelect from "../../components/linkageSelect";
import CitySelect from "../../components/citySelect.vue";
import SearchContent from "@/components/SearchContent/index.vue";
import workOrderDialog from "../components/addDialog/workOrderDialog.vue";
import {listDept} from "@/api/system/dept";
import {outChangeRentParam} from '@/api/finance/manage/collect/api.js';

export default {
  name: "NewCarInsuranceList",

  dicts: ["car_business_type", "work_order_type", "work_order_status"],
  components: {
    LinkageSelect,
    CitySelect,
    SearchContent,
    workOrderDialog,
  },
  computed: {
    dictsName() {
      return (arr, type) => {
        let name = "";
        arr.map((v) => {
          if (type == v.value) {
            name = v.label;
          }
        });
        return name;
      };
    },
    rowManage() {
      return (arr, type) => {
        let obj = {};
        let arri = [];
        arri = arr.filter((v) => {
          return v.type == type;
        });
        return (obj = arri[0] || {});
      };
    },
  },
  data() {
    return {
      //按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: false,

      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,

      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        carNoVinNo: "",
        procurementReportNumber: "",
        brandName: "",
        seriesName: "",
        modelName: "",
        contractReportNumber: "",
        belongCityName: "",
        workOrderStatus: "1",
        customerName: "",
        workOrderType: "1",
        propertyRightId: "",
        ascriptionId: "",
        workOrderCode: "",
        flowBusinessId: ""
      },

      total: 0,
      dataList: [],

      linkageList: [],
      citySelection: [],
      // 表单参数
      form: {
        carId: "1",
        workOrderType: "1",
        brandName: "",
        seriesName: "",
        modelName: "",
        vinNo: "",
        carNo: "",
        engineNo: "",
        belongCityName: "",
        busniessType: "",
        procurementReportNumber: "",
        contractReportNumber: "",
        cars: [],
      },
      // 表单校验
      rules: {
        vinNo: [{required: true, message: "车架号不能为空", trigger: "blur"}],
        carNo: [{required: true, message: "车牌号不能为空", trigger: "blur"}],
        belongCityName: [
          {required: true, message: "车辆归属不能为空", trigger: "blur"},
        ],
        busniessType: [
          {required: true, message: "车辆状态不能为空", trigger: "blur"},
        ],
        procurementReportNumber: [
          {required: true, message: "采购禀议号不能为空", trigger: "blur"},
        ],
        contractReportNumber: [
          {required: true, message: "合同禀议号不能为空", trigger: "blur"},
        ],
        workOrderType: [
          {required: true, message: "工单类型不能为空", trigger: "blur"},
        ],
        brandName: [
          {
            required: true,
            message: "品牌/车型/车款不能为空",
            trigger: "blur",
          },
        ],
      },

      idList: [],
      objData: {},
      insuranceChannels: "",
      carIdList: [],
      companyOriginList: [],
      propertyRightName: ''
    };
  },
  created() {
    this.getList();
    this.getCompanyOrigin();
  },
  activated() {
    this.getList();
  },
  methods: {
    getCompanyOrigin() {
      listDept({
        deptType: "2", //组织类型（1部门 2公司）
        regionId: null, //所在城市（省市区id）
      }).then((res) => {
        this.companyOriginList = res.data;
      });
    },

    handleAdd() {
      this.$refs.refAddDialog.handleOpen(1);
    },

    handleDialog() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    // 表单重置
    reset() {
      this.form = {};
      this.resetForm("form");
    },

    //批量处理
    handleBatch() {
      if (this.idList.length > 0) {
        let obj = {
          htList: [],// this.objData.htList,
          idList: this.objData.workIdList,
          workOrderType: 1,
        };
        unifyCheck(obj).then((res) => {
          if (res) {
            this.insuranceChannels = this.objData.insuranceChannels[0];
            this._toPage({
              path: "/cwgd/insuranceInquiryDetails",
              name: "InsuranceInquiryDetails",
              query: {
                id: this.idList,
                carId: this.carIdList,
                insuranceChannels: this.insuranceChannels,
                type: "edit",
                propertyRightName: this.propertyRightName,
              },
            });
          } else {
            this.$message({
              message: "保险类型不一致,请重新勾选",
              type: "warning",
            });
          }
        });
      }
    },


    handleSelectionChange(val) {
      let htList = [], workIdList = [];
      let insuranceChannels = [];
      for (let i = 0; i < val.length; i++) {
        htList.push(val[i].contractReportNumber);
        workIdList.push(val[i].id)
        insuranceChannels.push(val[i].insuranceChannels);
      }

      this.objData = {
        htList: htList,
        workIdList: workIdList,
        insuranceChannels: insuranceChannels,
      };
      this.idList = val.map((a) => {
        return a.id;
      });
      this.carIdList = val.map((a) => {
        return a.carId;
      });
      this.propertyRightName = val[0].propertyRightName || ''
    },

    linkageChange(val) {
      this.linkageList = val;
      if (val) {
        this.queryParams.brandName = val[0] ? val[0].name : "";
        this.queryParams.seriesName = val[1] ? val[1].name : "";
        this.queryParams.modelName = val[2] ? val[2].name : "";
      } else {
        this.queryParams.brandName = "";
        this.queryParams.seriesName = "";
        this.queryParams.modelName = "";
      }
      this.$forceUpdate();
    },

    /** 查询测试单表列表 */
    getList() {
      this.loading = true;
      getInsuranceWorkList(this.queryParams)
          .then((res) => {
            if (res.code === 200) {
              const {rows, total} = res;
              this.dataList = rows;
              this.total = total;
              this.loading = false;
            }
          })
          .catch(() => {
            this.loading = false;
          });
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.citySelection = [];
      this.linkageList = [];
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        carNoVinNo: "",
        procurementReportNumber: "",
        brandName: "",
        seriesName: "",
        modelName: "",
        contractReportNumber: "",
        belongCityName: "",
        workOrderStatus: "1",
        customerName: "",
        workOrderType: "1",
        propertyRightId: "",
        ascriptionId: "",
        workOrderCode: "",
        flowBusinessId: ""
      };
      this.getList();
    },

    viewOpen(row, type) {
      if (!row.businessDataId) {
        this._toPage({
          path: "/cwgd/newCarInsuranceDetails",
          name: "NewCarInsuranceDetails",
          query: {
            id: row.id,
            type: "view",
            workOrderStatus: row.workOrderStatus,
            insuranceChannels: row.insuranceChannels,
            carId: row.carId,
            flowId: row?.flowId || null,
          },
        });
      } else {
        this._toPage({
          path: "/cwgd/newCarInsuranceDetails",
          name: "NewCarInsuranceDetails",
          query: {
            id: row.id,
            businessDataId: row.businessDataId,
            flowId: row?.flowId || null,
            type: "view",
            insuranceChannels: row.insuranceChannels,
            workOrderStatus: row.workOrderStatus,
            carId: row.carId
          },
        });
      }
    },
    handleWork(row) {
      if (!row.businessDataId) {
        this._toPage({
          path: "/cwgd/newCarInsuranceDetails", //"/cwgd/insureHandle",
          name: "NewCarInsuranceDetails",
          query: {
            id: row.id,
            type: "edit",
            propertyRightName: row.propertyRightName,
            workOrderStatus: row.workOrderStatus,
            insuranceChannels: row.insuranceChannels,
            flowId: row?.flowId || null,
            carId: row.carId
          },
        });
      } else {
        this._toPage({
          path: "/cwgd/newCarInsuranceDetails",
          name: "NewCarInsuranceDetails",
          query: {
            id: row.id,
            businessDataId: row.businessDataId,
            type: "edit",
            propertyRightName: row.propertyRightName,
            workOrderStatus: row.workOrderStatus,
            insuranceChannels: row.insuranceChannels,
            flowId: row?.flowId || null,
            carId: row.carId
          },
        });
      }
    },

    /** 提交按钮 */
    submitForm() {
      this.form.workOrderType = "1";
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.buttonLoading = true;

          addInsuranceWork(this.form)
              .then((response) => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              })
              .finally(() => {
                this.buttonLoading = false;
              });
        }
      });
    },
    // /** 删除按钮操作 */
    // handleDelete(row) {
    //   const ids = row.id || this.ids;
    //   this.$modal.confirm('是否删除？').then(() => {
    //     this.loading = true;
    //     return delInsurance(ids);
    //   }).then(() => {
    //     this.loading = false;
    //     this.getList();
    //     this.$modal.msgSuccess("删除成功");
    //   }).finally(() => {
    //     this.loading = false;
    //   });
    // },

    /** 导出按钮操作 */
    handleExport() {
      this.download(
          "car/carWorkOrder/export",
          {
            ...this.queryParams,
          },
          `新车投保工单列表_${new Date().getTime()}.xlsx`
      );
    },
    getRowKeys() {
      return "id";
    },
    handleToContract(row) {
      this.$router.push({
        name: "SuborderDetail",
        query: {
          id: row.orderId,
          orderCarCode: row.orderCode
          ,
        },
      })
    },
    handleToProcurement(row) {
      if (row.procurementReportNumber && row.procurementReportNumber.startsWith("WBZZL")) {
        outChangeRentParam({code: row.procurementReportNumber}).then(res => {
          if (res && res.data && res.data.id) {
            this._toPage({
              path: '/purchaseRentManage/Sublease/SubleaseView',
              name: "SubleaseView",
              query: {
                type: "view",
                id: res.data.id,
              },
            });
          }
        })
      } else {
        this._toPage({
          name: "PurchaseAdd",
          query: {
            purchaseOrderId: row.purchaseOrderId,
            type: "detail",
            pageType: "采购详情",
          },
        });
      }

    },
  },
};
</script>
<style lang="scss" scoped>
.el-form {
  padding: 18px 20px;
  padding-bottom: 8px;
  background-color: #fff;
  border-radius: 8px;
  margin-bottom: 16px;

  ::v-deep .el-form-item {
    margin-bottom: 10px;
  }

  ::v-deep .el-form-item__label {
    font-size: 14px;
    font-family: 400;
  }
}
</style>
